package com.jiuwan.gamepass.controllerUtils;

import com.jiuwan.gamepass.dto.appJson.CommonJson;
import com.jiuwan.gamepass.utils.DownloadUtil;
import com.jiuwan.gamepass.utils.MyCode;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

/**
 * @version 1.0
 * 功能目的描述 ：用于         ========>>>>>>>>>>>
 * @author： pang-yun
 * @date： 2021-06-24 15:45
 */
@Controller
public class DownloadController {

    @RequestMapping("downloadFromUrl")
    @ResponseBody
    public CommonJson downloadFromUrl(String urlStr, String savePath) throws IOException {
        if (urlStr==null ||  savePath==null){
            CommonJson commonJson = new CommonJson();
            commonJson.setCode(MyCode.FAIL_CODE);
            commonJson.setMsg("请按格式输入参数");
            return commonJson;
        }
        CommonJson commonJson = DownloadUtil.downLoadFromUrl(urlStr,  savePath);
        return commonJson;
    }

    @GetMapping("download")
    public void download (String url, HttpServletResponse response) throws IOException {
        URL urlPath = ResourceUtils.getURL(url);
        //获取文件输入流
        FileInputStream  is= new FileInputStream(String.valueOf(urlPath));
        //获取相应输出流
        ServletOutputStream os = response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

